package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        //2.定义队列
        c.queueDeclare("task_queue",true,false,false,null);

        //3.准备好回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到："+s);
                //遍历字符串 找到 “。“ 字符暂停一秒
                for (int i = 0; i < s.length(); i++) {
                   if ('.' == s.charAt(i)){
                       try {
                           Thread.sleep(1000);
                       }catch (Exception e){
                           e.printStackTrace();
                       }
                   }
                }
                //1.回执数据 2，是否确认以前收到的所有消息  回执数据会存储到消息对象中
                //第二个参数是是否  对以前的参数进行确认
                c.basicAck(message.getEnvelope().getDeliveryTag(),false);




                System.out.println("接收消息完毕！");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        //qos =1 每次收一条 处理完之前不收下一条
        //每次抓取的消息数量
        c.basicQos(1);
        //4.消费消息
        //autoAck 自动ack true   false  ----是手动ack 这个时候需要手动发回回执
        c.basicConsume("task_queue",false, deliverCallback, cancelCallback);

    }


}
